package appnode;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;
import javax.servlet.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import appnode.Node;
import appnode.Interface;
import appnode.SearchNode;
import appnode.PMF;

public class Addif extends HttpServlet {


	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
	String nodename = req.getParameter("nodename");
	String action = req.getParameter("action");
	String name = req.getParameter("name");
	String protocol = req.getParameter("protocol");
	String direction = req.getParameter("direction");
	
	req.setAttribute("name",name);
	req.setAttribute("nodename",nodename);
	/*ServletContext sc = getServletContext();
	RequestDispatcher rd = sc.getRequestDispatcher(url);*/
	
	
	if (action.equals("new")) {
		    resp.sendRedirect("/addif.jsp?nodename="+nodename);	
	} // new
	else if (action.equals("update")) {
		;
	} // update
	else if (action.equals("save")) {
		PersistenceManager pm = PMF.get().getPersistenceManager();	
		Node node = SearchNode.getByName(nodename);
		int c = 0;
		// check ifname
		for (int j=0;j<node.getInterfaces().size();j++) {
			if (node.getInterfaces().get(j).getName().equals(name)) {
				c++;
			}
		}
		// valid name
		if (c==0) {
			Interface i = new Interface(name, protocol,direction,new Date());
			node.getInterfaces().add(i);
			pm.close();
			resp.setContentType("text/html");
			resp.getWriter().println("<html>");
			resp.getWriter().println("<head><title>Add interface</title></head>");
			resp.getWriter().println("<div style='font-family:Verdana;font-size: smaller;'>You add the interface succesfully</div>");
			resp.getWriter().println("<br>");
			resp.getWriter().println("<input type='button' value='Close' onClick='self.close()'/>");
			resp.getWriter().println("</html>");
		}
		else {
			/*resp.setContentType("text/html");
			resp.getWriter().println("<html>");
			resp.getWriter().println("name wrong, try again");
			resp.getWriter().println("<script>alert('name wrong')</script>");
			resp.getWriter().println("</html>");*/
			/*String wrong = "name already exists";
			req.setAttribute("wrong",wrong);
			sc = getServletContext();
			rd = sc.getRequestDispatcher(url);
			rd.forward(req, resp);*/
			resp.sendRedirect("/addif.jsp?nodename="+nodename);
		}		
	} // save
	
	}
	
}